Python3输入以空格为结束标志的方法 您所在的位置:网站首页 py input怎么用 Python3输入以空格为结束标志的方法

Python3输入以空格为结束标志的方法

#Python3输入以空格为结束标志的方法| 来源: 网络整理| 查看: 265

黑洞内窥:

          很多题目要求,输入一个n,然后接着输入n个整数,如:

          5

         1  2  3  4  5

         用input()输入如何将这5个数隔开呢?(input是整行输入,且输入为字符串)

 

思维光年:

   解决方法一:使用split()

  

n = int(input())#输入整数n ans = input() if len(ans.split())==n: a = [int(i) for i in ans.split()] print(n) print(ans) print(a)

 示例截图:

这样就可以将字符串“1 5 6 8 9”中的五个数字变成5个int变量存储在a列表中了

 

解决方法二:使用map

a,b=map(int,input().split())

可以添加变量:

a,b,c=map(int,input().split())

也可以格式输入,如用逗号‘,’隔开:

a,b,c=map(int,input().split(','))

或者这样:

n = int(input()) ans = list(map(int, input().split())) print(n) print(ans)

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有